/****************************************************************************************
*	Mouzetrap - client/server framework	
*
*	$HeadURL: http://mouzetrap.googlecode.com/svn/trunk/Mouzetrap/Threading/TaskPool.cs $
*	$Id: TaskPool.cs 11 2009-06-11 09:10:25Z tobz@fallenrealms.net $
* 
*	Copyright (c) 2008 Toby Lawrence
* 
*	Permission is hereby granted, free of charge, to any person obtaining a copy
*	of this software and associated documentation files (the "Software"), to deal
*	in the Software without restriction, including without limitation the rights
*	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
*	copies of the Software, and to permit persons to whom the Software is
*	furnished to do so, subject to the following conditions:
* 
*	The above copyright notice and this permission notice shall be included in
*	all copies or substantial portions of the Software.
* 
*	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
*	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
*	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
*	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
*	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
*	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
*	THE SOFTWARE.
* 
****************************************************************************************/

using System;
using System.Diagnostics;
using System.Threading;
using Mouzetrap.DataStructures;
using Mouzetrap.Localization;
using Mouzetrap.Threading;

namespace Mouzetrap
{
	public class TaskPool<T> where T : ITask
	{
		private readonly Stopwatch _highPrecisionTimer;
		private readonly LockfreeQueue<T> _taskQueue;
		private readonly int _tickInterval;
		private readonly WaitHandle _tpWaitHandle;
		private volatile bool _reportSlowdowns;
		private volatile bool _running;

		public TaskPool(int tickInterval, bool reportSlowdowns)
		{
			if(tickInterval < 1)
				throw new ArgumentOutOfRangeException("tickInterval", Mouzetrap_Messages.TaskPoolTickInterval);

			_highPrecisionTimer = new Stopwatch();
			_tpWaitHandle = new EventWaitHandle(false, EventResetMode.ManualReset);
			_tickInterval = tickInterval;
			_reportSlowdowns = reportSlowdowns;
			_taskQueue = new LockfreeQueue<T>();
		}

		public void StartPool()
		{
			_running = true;
			_highPrecisionTimer.Start();

			ThreadPool.RegisterWaitForSingleObject(_tpWaitHandle, PoolCallback, this, _tickInterval, true);
		}

		public void StopPool()
		{
			_running = false;
			_highPrecisionTimer.Reset();
		}

		protected virtual void PoolCallback(object state, bool timedOut)
		{
			if(!_running)
				return;

			OnBeforePoolCallback();

			long startTime = _highPrecisionTimer.ElapsedMilliseconds;

			WorkerCallback();

			long endTime = _highPrecisionTimer.ElapsedMilliseconds;

			if((endTime - startTime) > _tickInterval)
			{
				// we spent more time working than what we have for an execution interval
				if(_reportSlowdowns)
				{
					OnPoolSlowdown();
				}
			}

			OnAfterPoolCallback();

			ThreadPool.RegisterWaitForSingleObject(_tpWaitHandle, PoolCallback, this, _tickInterval, true);
		}

		protected virtual void WorkerCallback()
		{
			T task;

			while(_taskQueue.Dequeue(out task))
			{
				task.Execute();
			}
		}

		protected virtual void OnBeforePoolCallback()
		{
		}

		protected virtual void OnAfterPoolCallback()
		{
		}

		protected virtual void OnPoolSlowdown()
		{
			// some mock logging code for slowdown notifications:
			//
			// Logging.LoggingManager.GetLogger("TaskPool").WriteMessage(LogLevel.Trace, "slowdown on task pool");
			//
		}
	}
}